package com.easywork.jythonspring;

import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.apache.commons.lang.StringUtils;
import org.python.core.PySystemState;
import org.python.util.PythonInterpreter;
import org.springframework.beans.factory.InitializingBean;
/**
 * Python Intercepter Environment Initializer.
 * 
 * This class provided an isInitialized() method for program to decide whether the intercepter is ready
 * by spring's bean factory or call by manual some where before.
 * @author justicejiang
 *
 */
public class PythonInitializer implements InitializingBean{
	/**
	 * Python Home folder for cache storage
	 */
	private String pythonHome;
	
	/**
	 * Extension package for jython runtime environment
	 */
	private List<String> addPackages;
	/**
	 * Extension class path for jython runtime environment
	 */
	private List<String> addClassDirs;
	/**
	 * Extension jar or zip libs dir for jython runtime environment
	 */
	private List<String> addExtDirs;
	
	private static boolean initialized = false;
	
	public void afterPropertiesSet() throws Exception {
		//default python home
		if(StringUtils.isBlank(pythonHome))
			pythonHome = "/pythonHome";
		Properties props = new Properties();
		Properties sysProps = System.getProperties();
		if (sysProps.getProperty("python.home")==null) 
            sysProps.put("python.home", pythonHome); 
		
		for(Map.Entry<Object,Object> entry : sysProps.entrySet()){
			if(entry.getKey().toString().startsWith("python"))
				props.put(entry.getKey(), entry.getValue());
		}
		PythonInterpreter.initialize(sysProps, props, new String[0]);
		if(addPackages!= null && !addPackages.isEmpty())
			for(String addPackage : addPackages)
				if(StringUtils.isNotBlank(addPackage))
					PySystemState.add_package(addPackage);
		if(addClassDirs!= null && !addClassDirs.isEmpty())
			for(String addClassDir : addClassDirs)
				if(StringUtils.isNotBlank(addClassDir))
					PySystemState.add_package(addClassDir);
		if(addExtDirs!= null && !addExtDirs.isEmpty())
			for(String addExtDir : addExtDirs)
				if(StringUtils.isNotBlank(addExtDir))
					PySystemState.add_package(addExtDir);
		initialized = true;	
	}

	/**
	 * Indicates whether the Python environment has been initialized.
	 * @return
	 */
	public static boolean isInitialized() {
		return initialized;
	}
	
	public void setPythonHome(String pythonHome) {
		this.pythonHome = pythonHome;
	}

	public void setAddPackages(List<String> addPackage) {
		this.addPackages = addPackage;
	}

	public void setAddClassDirs(List<String> addClassDir) {
		this.addClassDirs = addClassDir;
	}

	public void setAddExtDirs(List<String> addExtDir) {
		this.addExtDirs = addExtDir;
	}

}
